﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.SessionState;

namespace RC1
{
    public partial class login : System.Web.UI.Page
    {
        public SqlConnection sqlCon;
        protected void Page_Load(object sender, EventArgs e)
        {
            errorLabel.Visible = false;
        }
        //hey
        private void connectToDB()
        {
            String connectionString = "Data Source=\"tsu2011.dk, 14821\";Initial Catalog=tsu2011db4;Persist Security Info=True;User ID=tsu2011sql4;Password=tsu2011pw4";
            sqlCon = new SqlConnection(connectionString);
            sqlCon.Open();
        }
        //sjsoi
        private Boolean checkLogin(String username, String password)
        {
            String q = "SELECT * FROM lpuser WHERE user_email='"+ username + "' AND user_password='"+ password +"'";
            SqlCommand myCommand = new SqlCommand(q, sqlCon);
            SqlDataReader myReader = myCommand.ExecuteReader();

            if (myReader.HasRows)
            {
                while (myReader.Read() != false)
                {
                    String id = myReader["user_id"].ToString();
                    String level = myReader["user_level"].ToString();
                    Session["user_id"] = id;
                    Session["user_level"] = level;
                    return true;
                }
                return true;
            }
            else
            {
                return false;
            }
        }

        private void loginToSystem()
        {
            String username = userTextBox.Text.Trim();
            String password = passwordTextBox.Text;
            connectToDB();
            Boolean b = checkLogin(username, password);
            if (!b)
            {
                printError("Skeivt brúkaranavn ella loyniorð");
            }
            else
            {
                if (Session["user_level"].Equals("2"))
                {
                    Response.Redirect("admin/Default.aspx");
                }
                else if (Session["user_level"].Equals("1"))
                {
                    Response.Redirect("teacher/Default.aspx");
                }

                else
                {
                    Response.Redirect("student/Default.aspx");
                }

            }
            
        }

        private void printError(String s)
        {
            errorLabel.Text = "<tr><td colspan='2' align='center'><span style='color:red;'>"+s+"</span></td></tr>";
            errorLabel.Visible = true;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            loginToSystem();
        }

    }
}